import logoPollingService from './logoPolling.js'
import axios from 'axios'
import { ElMessage } from 'element-plus'

/**
 * Logo生成功能使用示例
 * 供其他Vue页面参考使用
 */

/**
 * 示例1：在其他Vue页面中生成Logo（使用HTTP轮询）
 * @param {number} userId - 用户ID
 * @param {object} userData - 用户数据
 */
export const generateLogoWithPolling = async (userId, userData) => {
  try {
    // 1. 提交Logo生成请求
    const token = localStorage.getItem('token')
    const headers = token ? { 'Authorization': `Bearer ${token}` } : {}
    
    const logoRequest = {
      user_id: userId,
      gender: userData.gender,
      fitness_level: userData.fitness_level
    }
    
    const response = await axios.post(
      `http://localhost:8000/api/ai/generate-logo/${userId}/`,
      logoRequest,
      { headers }
    )
    
    if (response.data.success) {
      ElMessage.success('Logo生成请求已提交，正在获取进度...')
      
      // 2. 开始轮询进度
      logoPollingService.startPolling(
        userId,
        // 进度回调
        (progressData) => {
          console.log('Logo生成进度:', progressData)
          // 在这里更新UI显示进度
          // 例如：更新进度条、状态文本等
        },
        // 完成回调
        (result) => {
          console.log('Logo生成完成:', result)
          if (result.success) {
            ElMessage.success('Logo生成成功！')
            // 在这里更新UI显示结果
            // 例如：显示生成的Logo图片
          } else {
            ElMessage.error(result.message || 'Logo生成失败')
          }
        },
        // 错误回调
        (error) => {
          console.error('Logo生成错误:', error)
          ElMessage.error(error)
        }
      )
    } else {
      ElMessage.error(response.data.message || 'Logo生成请求失败')
    }
  } catch (error) {
    console.error('提交Logo生成请求失败:', error)
    ElMessage.error('提交Logo生成请求失败，请稍后重试')
  }
}

/**
 * 示例2：在Vue组件中使用（Composition API）
 */
export const useLogoGeneration = () => {
  const logoProgress = ref(0)
  const logoStatus = ref('')
  const logoMessage = ref('')
  const logoUrl = ref('')
  const isGenerating = ref(false)

  const generateLogo = async (userId, userData) => {
    if (isGenerating.value) {
      ElMessage.warning('Logo正在生成中，请稍候...')
      return
    }

    isGenerating.value = true
    logoProgress.value = 0
    logoStatus.value = 'preparing'
    logoMessage.value = '准备生成Logo...'

    try {
      const token = localStorage.getItem('token')
      const headers = token ? { 'Authorization': `Bearer ${token}` } : {}
      
      const logoRequest = {
        user_id: userId,
        gender: userData.gender,
        fitness_level: userData.fitness_level
      }
      
      const response = await axios.post(
        `http://localhost:8000/api/ai/generate-logo/${userId}/`,
        logoRequest,
        { headers }
      )
      
      if (response.data.success) {
        ElMessage.success('Logo生成请求已提交，正在获取进度...')
        
        logoPollingService.startPolling(
          userId,
          // 进度回调
          (progressData) => {
            logoProgress.value = progressData.progress || 0
            logoStatus.value = progressData.status || ''
            logoMessage.value = progressData.message || ''
          },
          // 完成回调
          (result) => {
            isGenerating.value = false
            if (result.success) {
              logoUrl.value = result.image_url
              logoProgress.value = 100
              logoStatus.value = 'success'
              logoMessage.value = 'Logo生成成功！'
              ElMessage.success('专属LOGO生成成功！')
            } else {
              logoStatus.value = 'error'
              logoMessage.value = result.message || 'Logo生成失败'
              ElMessage.error(result.message || 'Logo生成失败')
            }
          },
          // 错误回调
          (error) => {
            isGenerating.value = false
            logoStatus.value = 'error'
            logoMessage.value = error
            ElMessage.error(error)
          }
        )
      } else {
        isGenerating.value = false
        ElMessage.error(response.data.message || 'Logo生成请求失败')
      }
    } catch (error) {
      isGenerating.value = false
      console.error('Logo生成请求失败:', error)
      ElMessage.error('Logo生成请求失败，请稍后重试')
    }
  }

  const stopLogoGeneration = (userId) => {
    logoPollingService.stopPolling(userId)
    isGenerating.value = false
  }

  // 组件卸载时清理
  onUnmounted(() => {
    logoPollingService.stopAllPolling()
  })

  return {
    logoProgress,
    logoStatus,
    logoMessage,
    logoUrl,
    isGenerating,
    generateLogo,
    stopLogoGeneration
  }
}

/**
 * 示例3：在Vue组件中使用（Options API）
 */
export const logoGenerationMixin = {
  data() {
    return {
      logoProgress: 0,
      logoStatus: '',
      logoMessage: '',
      logoUrl: '',
      isGenerating: false
    }
  },
  
  methods: {
    async generateLogo(userId, userData) {
      if (this.isGenerating) {
        ElMessage.warning('Logo正在生成中，请稍候...')
        return
      }

      this.isGenerating = true
      this.logoProgress = 0
      this.logoStatus = 'preparing'
      this.logoMessage = '准备生成Logo...'

      try {
        const token = localStorage.getItem('token')
        const headers = token ? { 'Authorization': `Bearer ${token}` } : {}
        
        const logoRequest = {
          user_id: userId,
          gender: userData.gender,
          fitness_level: userData.fitness_level
        }
        
        const response = await axios.post(
          `http://localhost:8000/api/ai/generate-logo/${userId}/`,
          logoRequest,
          { headers }
        )
        
        if (response.data.success) {
          ElMessage.success('Logo生成请求已提交，正在获取进度...')
          
          logoPollingService.startPolling(
            userId,
            // 进度回调
            (progressData) => {
              this.logoProgress = progressData.progress || 0
              this.logoStatus = progressData.status || ''
              this.logoMessage = progressData.message || ''
            },
            // 完成回调
            (result) => {
              this.isGenerating = false
              if (result.success) {
                this.logoUrl = result.image_url
                this.logoProgress = 100
                this.logoStatus = 'success'
                this.logoMessage = 'Logo生成成功！'
                ElMessage.success('专属LOGO生成成功！')
              } else {
                this.logoStatus = 'error'
                this.logoMessage = result.message || 'Logo生成失败'
                ElMessage.error(result.message || 'Logo生成失败')
              }
            },
            // 错误回调
            (error) => {
              this.isGenerating = false
              this.logoStatus = 'error'
              this.logoMessage = error
              ElMessage.error(error)
            }
          )
        } else {
          this.isGenerating = false
          ElMessage.error(response.data.message || 'Logo生成请求失败')
        }
      } catch (error) {
        this.isGenerating = false
        console.error('Logo生成请求失败:', error)
        ElMessage.error('Logo生成请求失败，请稍后重试')
      }
    },

    stopLogoGeneration(userId) {
      logoPollingService.stopPolling(userId)
      this.isGenerating = false
    }
  },

  beforeUnmount() {
    logoPollingService.stopAllPolling()
  }
}
